use crate::pb::hello_service_server::{HelloService, HelloServiceServer};
use crate::pb::{HelloRequest, HelloResponse};
use tonic::transport::Server;

mod pb;

#[derive(Debug, Default)]
pub struct MyService {}

#[tonic::async_trait]
impl HelloService for MyService {
    async fn hello(
        &self,
        request: tonic::Request<HelloRequest>,
    ) -> Result<tonic::Response<HelloResponse>, tonic::Status> {
        let name = request.into_inner().name;
        // 返回以HelloReply为类型的示例作为响应
        println!("Got a request: {:?}", name);

        let reply = HelloResponse {
            result: format!("Hello {}!", name), // 由于gRPC请求和响应中的字段都是私有的，所以需要使用 .into_inner()
        };

        Ok(tonic::Response::new(reply)) // 发回格式化的问候语
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr = "127.0.0.1:7878".parse()?;
    let greeter = MyService::default();

    Server::builder()
        .add_service(HelloServiceServer::new(greeter))
        .serve(addr)
        .await?;

    Ok(())
}
